package com.p7.framework.permission.web.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/test")
public class TestLoginController {

    private static final Logger log = LoggerFactory.getLogger(TestLoginController.class);

    @RequestMapping("/login")
    @ResponseBody
    public Object login4Hotel(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {

            if (subject.isAuthenticated()) {
                log.info("------------------------------------------------------");
                log.info("------------------------------------------------------");
                log.info("------------------------------------------------------");
                subject.logout();
            }
            subject.login(token);

            SecurityUtils.getSubject().getSession().setAttribute("auth", "hahha");
            return "success";

        } catch (UnknownAccountException e) {
            return "用户名或者密码错误";
        } catch (IncorrectCredentialsException e) {
            return "登录失败";
        } catch (LockedAccountException e) {
            return "用户已锁定";
        } catch (DisabledAccountException e) {
            return "用户名或者密码错误";
        } catch (ExcessiveAttemptsException e) {
            return "ExcessiveAttemptsException";
        } catch (AuthenticationException e) {
            return "认证失败";
        } catch (Exception e) {
            return "账号异常";
        }
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Object testLogout() {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return "success";
    }

}
